package cn.edu.ncu.housinghub.mapper;

import cn.edu.ncu.housinghub.entity.user.Agent;
import cn.edu.ncu.housinghub.entity.user.AgentVerification;
import jakarta.validation.constraints.NotNull;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface AgentMapper {

    /**
     * 根据id查询中介信息
     * @param agentId
     */
    @Select("SELECT * FROM agent WHERE agentId = #{agentId}")
    Agent selectById(Long agentId);

    void insertNewAgent(Long userId);
    // 插入申请信息
    @Insert("insert into agentVerification(userId,licenseNo,licensePicPath,phone,companyName," +
            "companyPosition,realName,idCard,email,city,workYears,applyTime,verifyStatus,isDeleted)" +
            "values(#{userId},#{licenseNo},#{licensePicPath},#{phone},#{companyName}," +
            "#{companyPosition},#{realName},#{idCard},#{email},#{city},#{workYears}," +
            "#{applyTime},#{verifyStatus},#{isDeleted})")
    void insertApply(AgentVerification agentVerification);

    // 根据id获取申请信息（只查询未删除的记录，取最新的一条）
    @Select("select agentVerifyId,userId,licenseNo,licensePicPath,phone,companyName," +
            "companyPosition,realName,idCard,email,city,workYears,applyTime,refuseReason,verifyStatus,isDeleted" +
            " from agentverification where userId = #{userId} and (isDeleted = 0 or isDeleted is null) " +
            "order by agentVerifyId desc limit 1")
    AgentVerification selectApplyResult(@NotNull(message = "用户ID不能为空") Long userId);

    // 获取所有申请信息（只查询未删除的记录）
    @Select("select agentVerifyId,userId,licenseNo,licensePicPath,phone,companyName," +
            "companyPosition,realName,idCard,email,city,workYears,applyTime,refuseReason,verifyStatus,isDeleted" +
            " from agentverification where (isDeleted = 0 or isDeleted is null)")
    List<AgentVerification> selectAllApply();

    // 根据id更新申请状态（只更新未删除的记录）
    @Update("update agentverification set verifyStatus = #{verifyStatus},refuseReason=#{refuseReason} " +
            "where userId = #{userId} and (isDeleted = 0 or isDeleted is null)")
    void updateApplyStatusById(@Param("userId") Long userId,
                               @Param("verifyStatus") Integer verifyStatus,
                               @Param("refuseReason") String refuseReason);

    // 根据营业执照编号查询申请信息（只查询未删除的记录，取最新的一条）
    @Select("select * " +
            "from agentverification where licenseNo = #{licenseNo} and (isDeleted = 0 or isDeleted is null) " +
            "order by agentVerifyId desc limit 1")
    AgentVerification selectApplyByLicenseNo(String licenseNo);

    // 软删除用户的所有申请记录
    @Update("update agentverification set isDeleted = 1 where userId = #{userId} and (isDeleted = 0 or isDeleted is null)")
    void softDeleteApplyByUserId(@Param("userId") Long userId);
}
